package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.WebSocketUserApplication;
import com.ruoyi.teaching.domain.WebSocketUserDialogue;
import com.ruoyi.teaching.domain.vo.ApplicationUserVO;
import com.ruoyi.li.work.domain.vo.AppliedUserVO;
import com.ruoyi.teaching.mapper.WebSocketTemporaryMessageMapper;
import com.ruoyi.teaching.mapper.WebSocketUserApplicationMapper;
import com.ruoyi.teaching.mapper.WebSocketUserDialogueMapper;
import com.ruoyi.teaching.service.WebSocketUserApplicationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 李志鑫
 * @since 2024-08-23
 */
@Service
@Slf4j
public class WebSocketUserApplicationServiceImpl extends ServiceImpl<WebSocketUserApplicationMapper, WebSocketUserApplication> implements WebSocketUserApplicationService {
    @Autowired
    private WebSocketUserApplicationMapper webSocketUserApplicationMapper;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private WebSocketUserDialogueMapper webSocketUserDialogueMapper;

    @Autowired
    private WebSocketTemporaryMessageMapper webSocketTemporaryMessageMapper;
    @Override
    public AjaxResult selectAppliedUser(Integer pageNum, Integer pageSize, Long schoolId, Long roleId, String message) {
        Long userId = SecurityUtils.getUserId();
        Page<AppliedUserVO> page = new Page<>(pageNum, pageSize);
        List<AppliedUserVO> appliedUserVOS = sysUserMapper.selectAppliedUser(schoolId, roleId, message, userId);
        List<Long> ids = webSocketUserApplicationMapper.selectApplicationBYUserId(userId);
        appliedUserVOS.removeIf(user -> ids.contains(user.getUserId()));
        appliedUserVOS.removeIf(user -> user.getUserId() == userId);
        // 4. 手动分页
        int total = appliedUserVOS.size(); // 总记录数
        int fromIndex = (int) ((pageNum - 1) * pageSize); // 起始索引
        int toIndex = Math.min(fromIndex + pageSize, total); // 结束索引（防止越界）

        // 截取当前页的数据
        List<AppliedUserVO> paginatedList = appliedUserVOS.subList(fromIndex, toIndex);

        // 5. 填充分页对象
        page.setRecords(paginatedList);
        page.setTotal(total);
        return new AjaxResult(HttpStatus.SUCCESS, "成功",page);
    }

    @Override
    public AjaxResult applicationAddUser(WebSocketUserApplication webSocketUserApplication) {
        Long userId = SecurityUtils.getUserId();
        webSocketUserApplication.setApplicationUserId(userId);
        QueryWrapper<WebSocketUserApplication> webSocketUserApplicationQueryWrapper = new QueryWrapper<>();
        webSocketUserApplicationQueryWrapper.eq("applied_user_id", webSocketUserApplication.getAppliedUserId());
        webSocketUserApplicationQueryWrapper.eq("application_user_id", userId);
        webSocketUserApplicationQueryWrapper.and(w -> w.eq("state", 0).or().eq("state", 2));
        Long aLong = webSocketUserApplicationMapper.selectCount(webSocketUserApplicationQueryWrapper);
        if (aLong > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "申请添加好友成功");
        }
        Integer insert = webSocketUserApplicationMapper.insert(webSocketUserApplication);
        if (insert == 0) {
            return new AjaxResult(HttpStatus.ERROR, "申请失败");
        }
        return new AjaxResult(HttpStatus.SUCCESS, "申请成功");
    }

    @Override
    public AjaxResult selectApplicationAddUser(Integer pageNum, Integer pageSize) {
        Page<ApplicationUserVO> webSocketUserApplicationPage = new Page<>(pageNum, pageSize);
        Long userId = SecurityUtils.getUserId();
        Page<ApplicationUserVO> webSocketUserApplications = webSocketUserApplicationMapper.selectApplicationAddUser(webSocketUserApplicationPage, userId);
        return new AjaxResult(HttpStatus.SUCCESS, "查询成功", webSocketUserApplications);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateApplicationAddUser(WebSocketUserApplication webSocketUserApplication) {
            Integer i = webSocketUserApplicationMapper.updateById(webSocketUserApplication);
            if (i == 0) {
                return new AjaxResult(HttpStatus.ERROR, "修改失败");
            }
            if (webSocketUserApplication.getState() == 2) {
                WebSocketUserApplication webSocketUserApplication1 = webSocketUserApplicationMapper.selectById(webSocketUserApplication.getId());
                SysUser sysUser = sysUserMapper.selectUserById(webSocketUserApplication1.getApplicationUserId());
                SysUser sysUser1 = sysUserMapper.selectUserById(webSocketUserApplication1.getAppliedUserId());
                WebSocketUserDialogue webSocketUserDialogue = new WebSocketUserDialogue();
                webSocketUserDialogue.setAUserId(webSocketUserApplication1.getApplicationUserId());
                webSocketUserDialogue.setAUserName(sysUser.getUserName());
                webSocketUserDialogue.setAUserRemarks(sysUser.getNickName());
                webSocketUserDialogue.setBUserId(webSocketUserApplication1.getAppliedUserId());
                webSocketUserDialogue.setBUserName(sysUser1.getUserName());
                webSocketUserDialogue.setBUserRemarks(sysUser1.getNickName());
                QueryWrapper<WebSocketUserDialogue> webSocketUserDialogueQueryWrapper = new QueryWrapper<>();
                webSocketUserDialogueQueryWrapper.and(w -> w.eq("a_user_id", webSocketUserApplication1.getApplicationUserId()).or().eq("b_user_id", webSocketUserApplication1.getAppliedUserId())).or().and(z -> z.eq("a_user_id", webSocketUserApplication1.getAppliedUserId()).or().eq("b_user_id", webSocketUserApplication1.getApplicationUserId()));
                List<WebSocketUserDialogue> webSocketUserDialogues = webSocketUserDialogueMapper.selectList(webSocketUserDialogueQueryWrapper);
                List<WebSocketUserDialogue> tempDialogues = webSocketUserDialogueMapper.selectUserDialogueBy(webSocketUserApplication1.getApplicationUserId(), webSocketUserApplication1.getAppliedUserId(), 3);
                if (tempDialogues.size() > 0) {
                    for (WebSocketUserDialogue w: tempDialogues){
                        int s = webSocketUserDialogueMapper.deleteById(w.getId());
                        List<Integer> list = webSocketTemporaryMessageMapper.selectByDialogueId(w.getId());
                        if (!CollectionUtils.isEmpty(list)){
                            int k = webSocketTemporaryMessageMapper.deleteBatchIds(list);
                            if (k == 0){
                                throw new BaseException("500","删除临时消息失败");
                            }
                        }
                        log.info("删除临时消息对话框:"+s);
                    }
                }
                if (webSocketUserDialogues.size() > 0) {

                    return new AjaxResult(HttpStatus.SUCCESS, "好友已通过，请勿重复添加");
                }
                Integer insert = webSocketUserDialogueMapper.insert(webSocketUserDialogue);
                if (insert == 0) {
                    throw new BaseException("500", "添加失败");
                }
            }
            return new AjaxResult(HttpStatus.SUCCESS, "成功");
    }


}
